package com.example.nettyudp.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;

/**
 * @author FDJ,
 * @date 2020/5/26,
 * @time 9:39
 */
@Slf4j
public class NettyServer {

    @Autowired
    NettyServerHandler nettyServerHandler;

    public void start(InetSocketAddress port) {
        try {
            new Thread(() -> {
                EventLoopGroup group = new NioEventLoopGroup();
                try {
                    Bootstrap b = new Bootstrap();
                    b.group(group).channel(NioDatagramChannel.class)
                            .option(ChannelOption.SO_BROADCAST, true)
                            .handler(nettyServerHandler);

                    b.bind(port.getAddress(), port.getPort()).sync().channel().closeFuture().await();
                    System.out.println("netty udp server 启动成功");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    group.shutdownGracefully();
                }
            }).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
